﻿using D.IdentityDbStore.Stores;
using D.IdentityDbStore.Tokens;
using IdentityServer4.Stores;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using D.IdentityDbStore.DbContext;
using D.IdentityDbStore.Options;

namespace  D.IdentityDbStore.Extensions
{
    /// <summary>
    /// 扩展方法添加db支持IdentityServer
    /// </summary>
    public static class IdentityServerDbStoreExtensions
    {
        /// <summary>
        /// 配置接口和实现
        /// </summary>
        /// <param name="builder">The builder.</param>
        /// <param name="storeOptionsAction">存储配置信息</param>
        /// <returns></returns>
        public static IIdentityServerBuilder AddDbStore(
            this IIdentityServerBuilder builder, DbStoreOptions options)
        {
            builder.Services.AddSingleton(options);
            builder.Services.AddTransient<DbSql>();

            //操作客户端信息
            builder.Services.AddTransient<IClientStore, ClientStore>();
            //操作资源信息
            builder.Services.AddTransient<IResourceStore, ResourceStore>();
            //操作授权信息
            builder.Services.AddTransient<IPersistedGrantStore, PersistedGrantStore>();
            //操作设备信息
            builder.Services.AddTransient<IDeviceFlowStore, DeviceFlowStore>();

            //跨域处理
            builder.AddCorsPolicyService<CorsPolicyService>();

            //清理过期授权信息
            builder.Services.AddTransient<IExpiredAuthorization, ExpiredAuthorization>();

            builder.Services.AddTransient<TokenCleanupHelper>();
            //清理过期Token
            builder.Services.AddSingleton<IHostedService, TokenCleanupHostService>();
           

            return builder;
        } 
    }
}
